import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:developer' as developer;

/// App生命周期检测服务
/// 用于判断app是前台还是后台运行，决定通知显示方式
class AppLifecycleService extends GetxService with WidgetsBindingObserver {
  static AppLifecycleService get to => Get.find();

  // app生命周期状态
  final Rx<AppLifecycleState> _lifecycleState = AppLifecycleState.resumed.obs;
  AppLifecycleState get lifecycleState => _lifecycleState.value;

  // 是否在前台运行
  bool get isInForeground => _lifecycleState.value == AppLifecycleState.resumed;
  
  // 是否在后台运行
  bool get isInBackground => _lifecycleState.value == AppLifecycleState.paused || 
                           _lifecycleState.value == AppLifecycleState.detached;

  @override
  Future<void> onInit() async {
    super.onInit();
    
    // 注册生命周期观察者
    WidgetsBinding.instance.addObserver(this);
    
    // 获取当前生命周期状态
    _lifecycleState.value = WidgetsBinding.instance.lifecycleState ?? AppLifecycleState.resumed;
    
    developer.log('🔄 AppLifecycleService初始化完成');
    developer.log('📱 当前app状态: ${_getLifecycleStateText(_lifecycleState.value)}');
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    final previousState = _lifecycleState.value;
    _lifecycleState.value = state;
    
    developer.log('🔄 App生命周期状态变化: ${_getLifecycleStateText(previousState)} → ${_getLifecycleStateText(state)}');
    
    // 根据状态变化进行相应处理
    switch (state) {
      case AppLifecycleState.resumed:
        _onAppResumed();
        break;
      case AppLifecycleState.paused:
        _onAppPaused();
        break;
      case AppLifecycleState.detached:
        _onAppDetached();
        break;
      case AppLifecycleState.inactive:
        _onAppInactive();
        break;
      case AppLifecycleState.hidden:
        _onAppHidden();
        break;
    }
  }

  /// app进入前台
  void _onAppResumed() {
    developer.log('📱 App进入前台');
    // 可以在这里处理app恢复前台时的逻辑
    // 比如：清除系统通知、刷新数据等
  }

  /// app进入后台
  void _onAppPaused() {
    developer.log('📱 App进入后台');
    // 可以在这里处理app进入后台时的逻辑
    // 比如：保存数据、暂停定时器等
  }

  /// app被分离（即将关闭）
  void _onAppDetached() {
    developer.log('📱 App即将关闭');
  }

  /// app变为非活跃状态（如来电话、通知下拉等）
  void _onAppInactive() {
    developer.log('📱 App变为非活跃状态');
  }

  /// app被隐藏（iOS 特有）
  void _onAppHidden() {
    developer.log('📱 App被隐藏');
  }

  /// 获取生命周期状态文本描述
  String _getLifecycleStateText(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        return '前台运行';
      case AppLifecycleState.paused:
        return '后台运行';
      case AppLifecycleState.detached:
        return '即将关闭';
      case AppLifecycleState.inactive:
        return '非活跃状态';
      case AppLifecycleState.hidden:
        return '隐藏状态';
    }
  }

  /// 获取当前状态的描述信息
  String getCurrentStateDescription() {
    return _getLifecycleStateText(_lifecycleState.value);
  }

  /// 检查是否应该显示系统通知
  /// 返回true表示应该显示系统通知（app在后台）
  /// 返回false表示应该显示app内通知（app在前台）
  bool shouldShowSystemNotification() {
    final shouldShow = isInBackground;
    
    // 🔥 增加详细的状态检查日志
    developer.log('🔔 =============== 通知显示策略详细检查 ===============');
    developer.log('📱 当前生命周期状态: ${_getLifecycleStateText(_lifecycleState.value)}');
    developer.log('📱 isInForeground: $isInForeground');
    developer.log('📱 isInBackground: $isInBackground');
    developer.log('📱 shouldShow: $shouldShow');
    developer.log('🔔 最终策略: ${shouldShow ? "显示系统通知（app在后台）" : "显示app内通知（app在前台）"}');
    
    // 🔥 新增：如果状态为inactive，认为是前台（解决时序问题）
    if (_lifecycleState.value == AppLifecycleState.inactive) {
      developer.log('⚠️ 检测到inactive状态，可能是短暂的状态切换，强制使用前台通知');
      return false; // 强制使用前台通知
    }
    
    return shouldShow;
  }

  @override
  void onClose() {
    // 移除生命周期观察者
    WidgetsBinding.instance.removeObserver(this);
    super.onClose();
    developer.log('🔄 AppLifecycleService已销毁');
  }
}
